import * as querystring from 'querystring'
import * as moment from 'moment';
import { CommonData } from '../basicData/data'
import ls from './localStorage';
/**
 * 拼接查询字符串
 *
 * @param {Object} obj 查询数据对象
 * @return {string} 拼接后的字符串
 */
export const parseQuerystring = (obj: object) => {
  let result = ''

  const entries = (obj: any) => {
    let arr = [];
    for (let key of Object.keys(obj)) {
      arr.push([key, obj[key]]);
    }
    return arr;
  }
  if (obj) {
    const tmp: any = []
    const entriesArr = entries(obj)

    entriesArr.forEach((item: any) => {
      const key = item[0]
      const value = item[1]

      if (value instanceof Array && value.length) {
        value.forEach(v => {
          tmp.push(`${key}=${encodeURIComponent(v)}`)
        })
      } else {
        // tmp.push(`${key}=${encodeURIComponent(value)}`)
      }
    })

    result = tmp.join('&')
  }

  return result
}

/**
 * 获取url查询的值
 *
 * @param string  需要查询的字段
 */
export const getQuerystring = (name: string) => {
  const hash = window.location.hash;

  const num = hash.indexOf('?');

  const str = hash.slice(num + 1);

  const val = querystring.parse(str)[name];

  return val
}

/**
 * 日期处理
 * @param {*} date
 */
export const dateFormat = (date: any) => {
  return date
    ? moment(date).format('YYYY-MM-DD HH:mm:ss')
    : '--'
}

export const authObjectTreeRecombinant = (auths: any[]) => {
  let authObjectArray: any[] = [];
  if (auths.length && auths.length > 0) {
    auths.map(auth => {
      if (auth.childs.length > 0) {
        auth.currentNode.children = authObjectTreeRecombinant(auth.childs)
      }
      authObjectArray.push(auth.currentNode)
    })
  }
  return authObjectArray
}

export const getAuthObjectTreeSelect = (auths: any[]) => {
  let arr: any[] = [];
  if (auths && auths.length && auths.length > 0) {
    auths.map(auth => {
      let obj;
      obj = {
        title: auth.objectName,
        key: auth.id,
        value: auth.id,
        children: auth.children && auth.children.length > 0 ? getAuthObjectTreeSelect(auth.children) : []
      }
      arr.push(obj)
    })
  }
  return arr
}

export const listenECodePlatform = () => {
  window.addEventListener('message', function (e) {
    if (CommonData.QRCodeURL[process.env.NODE_ENV].indexOf(e.origin) < 0)
      return;
    if (typeof(e.data) === 'string') { 
      ls.clear()
      ls.set('href', e.data)
    }
  }, false);
}
/**
 * 过滤对象的参数值
 * @param obj 
 */
export const dealElement = (obj: any) => {
  const param: any = {};
  if ( obj === null || obj === undefined || obj === "" ) return param;
  for ( var key in obj ){
      if ( obj[key] !== null && obj[key] !== undefined && obj[key] !== "" ){
          param[key] = obj[key];
      }
  }
  return param;
}
